# -*- coding: utf-8 -*-
"""
@File:   logger.py.py
@Author: jk.dong
@Desc:   None
"""
import logging
import time
from logging.handlers import TimedRotatingFileHandler
from docwork.config import load_config, BASE_PATH


class MyLoggingHandler(TimedRotatingFileHandler):
    """
    自定义日志构造器
    """
    def __init__(self, filename_, when='h', interval=1, backup_count=0, encoding=None, delay=False, utc=False,
                 at_time=None):
        TimedRotatingFileHandler.__init__(self, filename_, when=when, interval=interval, backupCount=backup_count,
                                          encoding=encoding, delay=delay, utc=utc, atTime=at_time)

    def computeRollover(self, currentime):
        t_str = time.strftime(self.suffix, time.localtime(currentime))
        t = time.mktime(time.strptime(t_str, self.suffix))
        return TimedRotatingFileHandler.computeRollover(self, int(t))


def my_timed_rotating_file_handler(filename: str):
    # 配置文件初始化
    config_ = load_config(section='run-setting')
    logging.basicConfig()
    logs_dir = BASE_PATH / 'logs'
    if not logs_dir.exists():
        logs_dir.mkdir()
    fileHandler = MyLoggingHandler(filename_=logs_dir/f"{filename}.log", encoding="UTF-8", backup_count=int(config_['backup_count']))
    fileHandler.suffix = "%Y-%m-%d_%H.log"
    fileHandler.setLevel(logging.INFO)
    logFormatter = logging.Formatter("%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s")
    fileHandler.setFormatter(logFormatter)
    logging.getLogger('').addHandler(fileHandler)
    logging.getLogger('').setLevel(logging.INFO)
    return logging